package com.kxq.zhuoyue.util;

import com.alibaba.fastjson.JSONObject;
import com.kxq.zhuoyue.util.wechat.AccessToken;
import com.kxq.zhuoyue.util.wechat.JsApiTicket;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.util.Random;

public class WeChatUtil {
    //将消息发送给所有成员
    public final static String TOPARTY = "@all";
    //获取企业微信的企业号，根据不同企业更改
    public final static String CORPID = "ww52a4707ab1903788";
    //获取访问权限码URL
    public final static String ACCESS_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";

    public static AccessToken getAccessToken(String corpsecret) {
        AccessToken token = new AccessToken();

        //访问微信服务器
        String url = ACCESS_TOKEN_URL + "?corpid=" + CORPID + "&corpsecret=" + corpsecret;
        try {
            URL getUrl = new URL(url);
            //开启连接，并返回一个URLConnection对象
            HttpURLConnection http = (HttpURLConnection) getUrl.openConnection();
            http.setRequestMethod("GET");
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            //将URL连接用于输入和输出，一般输入默认为true，输出默认为false
            http.setDoOutput(true);
            http.setDoInput(true);
            //进行连接，不返回对象
            http.connect();
            //获得输入内容,并将其存储在缓存区
            InputStream inputStream = http.getInputStream();
            int size = inputStream.available();
            byte[] buffer = new byte[size];
            inputStream.read(buffer);
            //将内容转化为JSON代码
            String message = new String(buffer, "UTF-8");

            JSONObject json = JSONObject.parseObject(message);

            //提取内容，放入对象
            token.setAccess_token(json.getString("access_token"));
            token.setExpires_in(new Integer(json.getString("expires_in")));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //返回access_token码
        return token;
    }

    public static JsApiTicket getTicket(String access_token, String type) {
        JsApiTicket token = new JsApiTicket();

        String url = "";
        //访问微信服务器
        if (type.equals("app")) {
            url = "https://qyapi.weixin.qq.com/cgi-bin/ticket/get?access_token=" + access_token + "&type=agent_config";
        } else {
            url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=" + access_token;
        }

        try {
            URL getUrl = new URL(url);
            //开启连接，并返回一个URLConnection对象
            HttpURLConnection http = (HttpURLConnection) getUrl.openConnection();
            http.setRequestMethod("GET");
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            //将URL连接用于输入和输出，一般输入默认为true，输出默认为false
            http.setDoOutput(true);
            http.setDoInput(true);
            //进行连接，不返回对象
            http.connect();

            //获得输入内容,并将其存储在缓存区
            InputStream inputStream = http.getInputStream();
            int size = inputStream.available();
            byte[] buffer = new byte[size];
            inputStream.read(buffer);
            //将内容转化为JSON代码
            String message = new String(buffer, "UTF-8");
            JSONObject json = JSONObject.parseObject(message);
            //提取内容，放入对象
            token.setTicket(json.getString("ticket"));
            token.setExpires_in(new Integer(json.getString("expires_in")));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //返回ticket码
        return token;
    }

    //sha1加密
    public static String shaEncode(String inStr) {
        MessageDigest sha = null;
        StringBuffer hexValue = new StringBuffer();
        try {
            sha = MessageDigest.getInstance("SHA");
            byte[] byteArray = inStr.getBytes("UTF-8");
            byte[] md5Bytes = sha.digest(byteArray);
            for (int i = 0; i < md5Bytes.length; i++) {
                int val = ((int) md5Bytes[i]) & 0xff;
                if (val < 16) {
                    hexValue.append("0");
                }
                hexValue.append(Integer.toHexString(val));
            }
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }


        return hexValue.toString();
    }

        //随机字符串
    public static String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }
}